package com.yonyou.crm.common.base;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.yonyou.crm.bpub.list.entity.AppListVO;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.filter.entity.AppFilterTypeConstant;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sys.modules.rmitf.IListLayoutRmService;

public class AppBaseCtrl {
	
	@Autowired
	IListLayoutRmService listLayoutService;
	
	/**
	 * 多选筛选类型
	 */
	private String[] filterValueArrayType = {
				AppFilterTypeConstant.Multiple, 
				AppFilterTypeConstant.PCDPicker, 
				AppFilterTypeConstant.DateRanger, 
				AppFilterTypeConstant.NumberRanger
			};
	
	/**
	 * 单选筛选类型
	 */
	private String[] filterValueStringType = {
				AppFilterTypeConstant.Radio, 
				AppFilterTypeConstant.Refer, 
				AppFilterTypeConstant.TreeRefer
			};

	/**
	 * 搜索关键字
	 * @param paramObject
	 * @param searchMap
	 */
	public void getSearchKeyForList(JSONObject paramObject, Map<String, Object> searchMap){
		if (paramObject.containsKey("condition")) {
			String condition = paramObject.getString("condition");
			if (condition != null) {
				String keyword = condition;
				if (!keyword.equals("")) {
					searchMap.put("appSearchKey", keyword);
				}
			}
		}
	}

	/**
	 * 列表筛选
	 * @param paramObject
	 * @param searchMap
	 * @throws CrmMessageException
	 */
	public void getFilterForList(JSONObject paramObject, Map<String, Object> searchMap) throws CrmMessageException{
		if (paramObject.containsKey("filter")) {
			JSONArray filterArray = paramObject.getJSONArray("filter");
			if (filterArray != null) {
				List<Map<String, Object>> filterList = JSONArray.toList(filterArray, new HashMap<String, Object>(), new JsonConfig());
				if (filterList != null) {
					for(int i = 0; i < filterList.size(); i++) {
						Map<String, Object> filter = filterList.get(i);
						getFilter(filter, searchMap);
					}
				}
			}
		}
	}
	
	/**
	 * 获取列表筛选条件取值
	 * @param filter
	 * @param searchMap
	 * @throws CrmMessageException
	 */
	public void getFilter(Map<String, Object> filter, Map<String, Object> searchMap) throws CrmMessageException {
		Object value = filter.get("id");
		String type = String.valueOf(filter.get("type"));
		String key = String.valueOf(filter.get("key"));
		if ((value != null) && (!String.valueOf(value).equals(""))) {
			if (Arrays.asList(filterValueStringType).contains(type)) {
				searchMap.put(key, value);
			} else if (AppFilterTypeConstant.DatePicker.equals(type)) {
				Date val = transformDateFromStr(String.valueOf(value), "yyyy-MM-dd");
				searchMap.put(key, val);
			} else if (Arrays.asList(filterValueArrayType).contains(type)){
				getFilterArrayValue(key, type, value, searchMap);
			} else {
				//nothing
			}
		}
	}
	
	/**
	 * 获取多值筛选条件
	 * @param key
	 * @param type
	 * @param value
	 * @param searchMap
	 * @throws CrmMessageException
	 */
	public void getFilterArrayValue(String key, String type, Object value, Map<String, Object> searchMap) throws CrmMessageException {
		JSONArray val = JSONArray.fromObject(value);
		List<String> valRange = JSONArray.toList(val, new String(), new JsonConfig());
		if ((valRange != null) && (valRange.size() != 0)) {
			if (AppFilterTypeConstant.Multiple.equals(type)) {
				searchMap.put(key, valRange);
			} else if (AppFilterTypeConstant.PCDPicker.equals(type)) {
				//省市区筛选条件处理
				searchMap.put("province", valRange.get(0));
				searchMap.put("city", valRange.get(1));
				searchMap.put("district", valRange.get(2));
			} else if (AppFilterTypeConstant.DateRanger.equals(type)) {
				searchMap.put(key+"Start", transformDateFromStr(valRange.get(0), "yyyy-MM-dd"));
				searchMap.put(key+"End", transformDateFromStr(valRange.get(1), "yyyy-MM-dd"));
			} else if (AppFilterTypeConstant.NumberRanger.equals(type)) {
				searchMap.put(key+"Start", valRange.get(0));
				searchMap.put(key+"End", valRange.get(1));
			}
		}
	}
	
	/**
	 * 列表数据分类
	 * @param paramObject
	 * @param searchMap
	 */
	public void getOptionForList(JSONObject paramObject, Map<String, Object> searchMap){
		if (paramObject.containsKey("option")) {
			String optionStr = paramObject.getString("option");
			if (optionStr != null) {
				int option = Integer.parseInt(optionStr);
				if (option != 0) {
					searchMap.put("option", option);
				}
			}
		}
	}
	
	/**
	 * 列表排序数据
	 * @param paramObject
	 * @param sortMap
	 * @throws CrmMessageException
	 */
	public void getSortForList(JSONObject paramObject, Map<String, String> sortMap) throws CrmMessageException{
		if (paramObject.containsKey("sort")) {
			Map<String, String> sortInfo = (Map<String, String>)paramObject.get("sort");
			if (sortInfo.get("field") != null) {
				String sort = String.valueOf(sortInfo.get("field"));
				if (sort != null && !sort.equals("")) {
					String orderStr = String.valueOf(sortInfo.get("order"));
					checkSortOrder(orderStr);
					sortMap.put("field", sort);
					sortMap.put("order", orderStr);
				}
			}
		}
	}
	
	/**
	 * 校验排序参数
	 * @param orderStr
	 * @return
	 * @throws CrmMessageException
	 */
	public boolean checkSortOrder(String orderStr) throws CrmMessageException {
		if (!orderStr.equals("desc") && !orderStr.equals("asc")) {
			throw new CrmMessageException(AppCodeConstant.ClientError, "排序参数错误");
		}
		return true;
	}
	
	/**
	 * 将String格式转换为Date格式
	 * @param dateStr
	 * @return
	 * @throws CrmMessageException
	 */
	public Date transformDateFromStr(String dateStr, String dateFormate) throws CrmMessageException{
		String[] dateFormateArr = {"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm"};
		if (!Arrays.asList(dateFormateArr).contains(dateFormate)) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "日期格式化格式错误");
		}
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormate);
		Date date;
		try{
			date = sdf.parse(dateStr);
		} catch(ParseException e) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "日期格式错误");
		}
		return date;
	}
	
	/**
	 * 格式化日期类型数据
	 * @param date
	 * @param dateFormate
	 * @return
	 * @throws CrmMessageException
	 */
	public String formateDate(Date date, String dateFormate) throws CrmMessageException{
		if (date == null) {
			return "";
		}
		String[] dateFormateArr = {"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm"};
		if (!Arrays.asList(dateFormateArr).contains(dateFormate)) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "日期格式化格式错误");
		}
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormate);
		return sdf.format(date);
	}
	
	/**
	 * 格式化金额类型数据
	 * @param price
	 * @return
	 */
	public String transformPrice(BigDecimal price) {
		if (price == null) {
			return "";
		}
		DecimalFormat df2 = new DecimalFormat("#,###.00");
        String priceStr = df2.format(price);
        return priceStr;
	}
	
	/**
	 * 新增对象时添加业务子类型参数（商机、线索、联系人）
	 * @param paramObject
	 * @param param
	 */
	public void setBizType(JSONObject paramObject, Map<String, Object> param) {
		if (paramObject.containsKey("subBnsType")) {
			String subBnsType = paramObject.getString("subBnsType");
			if ( subBnsType != null) {
				//TODO设置业务子类型
				param.put("subBnsType", subBnsType);
			}
		}
	}
	
	/**
	 * 校验分页信息
	 * @param page
	 * @param pageSize
	 * @throws CrmMessageException
	 */
	public void checkPageInfo(Integer page, Integer pageSize) throws CrmMessageException {
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		//TODO确认是否必须
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
	}
	
	/**
	 * 客户地址信息
	 * @param customer
	 * @return
	 */
	public String getAddressInfo(CustomerVO customer) {
		String address = "";
//		if (customer.getProvinceName() != null) {
//			address += customer.getProvinceName();
//		}
//		if (customer.getCityName() != null) {
//			address += customer.getCityName();
//		}
//		if (customer.getDistrictName() != null) {
//			address += customer.getDistrictName();
//		}
		if (customer.getStreet() != null) {
			address += customer.getStreet();
		}
		return address;
	}
	
	/**
	 * 获取列表模板
	 * @param objId
	 * @return
	 */
	public AppListVO getAppListLayout(Long objId) {
		return listLayoutService.getAppListVOForCurrentUser(objId);
	}
	
}
